# !/usr/bin/nev python
# -*-coding:utf8-*-

'''
1) album_title：音乐专辑名称
2) genre：专辑类型
3) year_of_pub： 专辑发行年份
4) num_of_tracks： 每张专辑中单曲数量
5) num_of_sales：专辑销量
6) rolling_stone_critic：滚石网站的评分
7) mtv_critic：全球最大音乐电视网MTV的评分
8) music_maniac_critic：音乐达人的评分
'''

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns

df = pd.read_csv('albums.csv')

# 1.数据清洗
print("原始数据基本信息:")
print(f"数据集形状: {df.shape}")
print("\n前5行数据:")
print(df.head())
print("\n数据基本信息:")
print(df.info())
print("\n数值列统计描述:")
print(df.describe())
# 统计并处理缺失值
print("缺失值统计:")
print(df.isnull().sum())
# 评分列用中位数填充
critic_cols = ['rolling_stone_critic', 'mtv_critic', 'music_maniac_critic']
for col in critic_cols:
    df[col]=df[col].fillna(df[col].median())
# 销量列用0填充
df['num_of_sales']=df['num_of_sales'].fillna(0)


# 2.1 统计各类型专辑数量
#柱状图
plt.figure(figsize=(12, 6))
genre_counts=df['genre'].value_counts()
genre_counts.plot(kind='bar', color='skyblue')
plt.title('Number of Albums by Genre')
plt.xlabel('Genre')
plt.ylabel('Count')
plt.xticks(rotation=45)
plt.grid(axis='y', linestyle='--', alpha=0.7)
plt.show()

#扇形图
plt.figure(figsize=(14, 14))
ax=genre_counts.plot(kind='pie',explode=[0.2]+[0]*(len(genre_counts.index)-1),startangle=90)
for text in ax.texts:
    text.set_fontsize(9)

num_categories = len(genre_counts)
colors = plt.cm.plasma(np.linspace(0, 1, num_categories))

for i, patch in enumerate(ax.patches):
    patch.set_color(colors[i])
ax.set_title('Number of Albums by Genre')
plt.show()

# 2.2 统计各类型专辑销量总数
#柱状图
genre_sales = df.groupby('genre')['num_of_sales'].sum().sort_values(ascending=False)
plt.figure(figsize=(12, 6))
genre_sales.plot(kind='bar', color='lightcoral')
plt.title('Total Sales by Genre')
plt.xlabel('Genre')
plt.ylabel('Total Sales (in millions)')
plt.xticks(rotation=45)
plt.grid(axis='y', linestyle='--', alpha=0.7)
plt.show()

#扇形图
plt.figure(figsize=(14, 14))
ax=genre_sales.plot(kind='pie',explode=[0.2]+[0]*(len(genre_sales.index)-1),startangle=90)
for text in ax.texts:
    text.set_fontsize(9)

num_categories = len(genre_sales)
colors = plt.cm.RdBu(np.linspace(0, 1, num_categories))

for i, patch in enumerate(ax.patches):
    patch.set_color(colors[i])
ax.set_title('Total Sales by Genre')
plt.show()

# 2.3 统计近20年每年发行的专辑数量和单曲数量
current_year = pd.to_datetime('today').year   #获取当下时间年份
recent_years = range(current_year - 19, current_year + 1)    #最近20年
recent_df = df[df['year_of_pub'].isin(recent_years)]    #筛选数据

albums_per_year = recent_df['year_of_pub'].value_counts().sort_index()  #排序
tracks_per_year = recent_df.groupby('year_of_pub')['num_of_tracks'].sum()  #按照年份分组求和

fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(12, 10))  #绘图
ax1.bar(albums_per_year.index.astype(str), albums_per_year.values, color='royalblue')
ax1.set_title('Number of Albums Released per Year (Last 20 Years)')
ax1.set_ylabel('Number of Albums')
ax1.grid(axis='y', linestyle='--', alpha=0.5)

ax2.bar(tracks_per_year.index.astype(str), tracks_per_year.values, color='orange')
ax2.set_title('Total Number of Tracks Released per Year (Last 20 Years)')
ax2.set_ylabel('Number of Tracks')
ax2.grid(axis='y', linestyle='--', alpha=0.5)

plt.tight_layout()
plt.show()

# 构造矩阵数据（年份为行，指标为列）
df_heat = pd.DataFrame({
    'Year': albums_per_year.index,
    'Albums': albums_per_year.values,
    'Tracks': tracks_per_year.values
}).set_index('Year')

# 热力图绘制
plt.figure(figsize=(12, 8))
sns.heatmap(
    df_heat,
    annot=True,
    fmt='d',
    cmap='YlGnBu',
    cbar_kws={'label': 'Count'}
)
plt.title('Albums & Tracks Heatmap (Last 20 Years)', fontsize=14)
plt.xlabel('Metric', fontsize=12)
plt.ylabel('Year', fontsize=12)
plt.tight_layout()
plt.show()

# 2.4 分析总销量前五的专辑类型的各年份销量
top5_genres = genre_sales.head(5).index
top5_df = df[df['genre'].isin(top5_genres)]
yearly_genre_sales = top5_df.groupby(['year_of_pub', 'genre'])['num_of_sales'].sum().unstack()

plt.figure(figsize=(14, 8))
for genre in top5_genres:
    plt.plot(yearly_genre_sales.index, yearly_genre_sales[genre], marker='o', label=genre)

plt.title('Yearly Sales of Top 5 Genres')
plt.xlabel('Year')
plt.ylabel('Sales (in millions)')
plt.legend()
plt.grid(True, linestyle='--', alpha=0.7)
plt.tight_layout()
plt.show()

# 2.5 分析总销量前五的专辑类型在不同评分体系中的平均评分
critic_columns = ['rolling_stone_critic', 'mtv_critic', 'music_maniac_critic']
genre_ratings = top5_df.groupby('genre')[critic_columns].mean()

x = np.arange(len(top5_genres))
width = 0.25

plt.figure(figsize=(16, 9))
bars1 = plt.bar(x - width, genre_ratings['rolling_stone_critic'], width, label='Rolling Stone',color='#ff6b6b')
bars2 = plt.bar(x, genre_ratings['mtv_critic'], width, label='MTV',color='#45b7de')
bars3 = plt.bar(x + width, genre_ratings['music_maniac_critic'], width, label='Music Maniac',color='#ffd166')

plt.title('Average Ratings by Critic for Top 5 Genres')
plt.xlabel('Genre')
plt.ylabel('Average Rating')
plt.xticks(x, top5_genres)
plt.legend()
plt.grid(axis='y', linestyle='--', alpha=0.7)
plt.tight_layout()
plt.show()

# 创建 1 行 3 列的子图，展示 3 个评论家的饼图
fig, axes = plt.subplots(1, 3, figsize=(18, 6))

# 评论家列表和颜色映射
critics = ['rolling_stone_critic', 'mtv_critic', 'music_maniac_critic']
colors_list = [
    ['#FF6B6B', '#4ECDC4', '#556270', '#FFD166', '#06D6A0'],
    ['#264653', '#2A9D8F', '#E9C46A', '#F4A261', '#E76F51'],
    ['#74B49B', '#E1B16A', '#AB4967', '#376996', '#F26440']
]

for i, critic in enumerate(critics):
    ax = axes[i]
    # 绘制分组饼图
    ax.pie(
        genre_ratings[critic],       # 当前评论家的评分数据
        labels=top5_genres,          # 流派标签
        autopct='%1.1f%%',           # 显示百分比
        startangle=90,              # 起始角度
        colors=colors_list[i]        # 每组不同配色
    )
    ax.set_title(f'{critic.replace("_", " ")} Ratings')  # 设置子图标题

plt.tight_layout()
plt.show()